from django.forms import model_to_dict
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import serializers

from api import models
from api import serializer


class Category(APIView):
    def get(self, request, *args, **kwargs):
        '''
        获取所有文章分类
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        id = request.query_params.get('id')
        if not request.query_params:
            queryset = models.Category.objects.all().values('id', 'name')
            data_list = list(queryset)
            return Response(data_list)
        category_obj = models.Category.objects.filter(id=id).first()
        data = model_to_dict(category_obj)
        return Response(data)

    def post(self, request, *args, **kwargs):
        '''
        增加一条分类信息
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        # 这样不管前端传什么格式的数据都可以正常保存，比较保险
        name = request.data.get('name')
        models.Category.objects.create(name=name)

        # 如果前端传的是json格式数据可以使用下面这种方式直接存储
        # models.Category.objects.create(**request.data)
        return Response('添加成功')

    def delete(self, request, *args, **kwargs):
        id = request.data.get('id')
        print('删除', id)
        models.Category.objects.filter(id=id).delete()
        return Response('删除成功')

    def put(self, request, *args, **kwargs):
        id = request.data.get('id')
        name = request.data.get('name')
        models.Category.objects.filter(id=id).update(name=name)
        return Response('更新成功')


class NewCategory(APIView):

    def get(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        if not request.query_params:
            queryset = models.Category.objects.all()
            print(list(queryset))
            ser = serializer.NewCategorySerializers(instance=queryset, many=True)
            return Response(ser.data)
        queryset = models.Category.objects.filter(id=id).first()
        ser = serializer.NewCategorySerializers(instance=queryset, many=False)
        return Response(ser.data)

    def post(self, request, *args, **kwargs):
        # 使用了Serializers就不用先取出来name了，如果前端穿了数据库字段就可以直接保存
        # name = request.data.get('name')
        ser = serializer.NewCategorySerializers(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def put(self, request, *args, **kwargs):
        id = request.data.get('id')
        queryset = models.Category.objects.filter(id=id).first()
        ser = serializer.NewCategorySerializers(instance=queryset, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def delete(self, request, *args, **kwargs):
        id = request.data.get('id')
        models.Category.objects.filter(id=id).delete()
        return Response('删除成功')


class Article(APIView):
    def get(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        if not request.query_params:
            queryset = models.Article.objects.all()
            ser = serializer.ArticleSerializers(instance=queryset, many=True)
            return Response(ser.data)
        queryset = models.Article.objects.filter(id=id).first()
        ser = serializer.ArticleSerializers(instance=queryset, many=False)
        return Response(ser.data)

    def post(self, request, *args, **kwargs):
        ser = serializer.ArticleSerializers(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def put(self, request, *args, **kwargs):
        '''
        全部更新
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        id = request.data.get('id')
        queryset = models.Article.objects.filter(id=id).first()
        ser = serializer.ArticleSerializers(instance=queryset, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def patch(self, request, *args, **kwargs):
        '''
        局部更新
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        id = request.data.get('id')
        queryset = models.Article.objects.filter(id=id).first()
        # partial=True加上这句话说明允许局部更新
        ser = serializer.ArticleSerializers(instance=queryset, data=request.data, partial=True)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def delete(self, request, *args, **kwargs):
        id = request.data.get('id')
        models.Article.objects.filter(id=id).first().delete()
        return Response('删除成功')


class NewArticle(APIView):
    def get(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        if not request.query_params:
            queryset = models.Article.objects.all()
            ser = serializer.NewArticleSerializers(instance=queryset, many=True)
            return Response(ser.data)
        queryset = models.Article.objects.filter(id=id).first()
        ser = serializer.NewArticleSerializers(instance=queryset, many=False)
        return Response(ser.data)

    def post(self, request, *args, **kwargs):
        # 暂时只能接受json的数组，不能接收其他如x-www-form-urlencoded传递的数组
        ser = serializer.PostArticleSerializers(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def put(self, request, *args, **kwargs):
        '''
        全部更新
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        id = request.data.get('id')
        queryset = models.Article.objects.filter(id=id).first()
        ser = serializer.PostArticleSerializers(instance=queryset, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def patch(self, request, *args, **kwargs):
        '''
        局部更新
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        id = request.data.get('id')
        queryset = models.Article.objects.filter(id=id).first()
        # partial=True加上这句话说明允许局部更新
        ser = serializer.PostArticleSerializers(instance=queryset, data=request.data, partial=True)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def delete(self, request, *args, **kwargs):
        id = request.data.get('id')
        models.Article.objects.filter(id=id).first().delete()
        return Response('删除成功')


from rest_framework.pagination import PageNumberPagination

# class Page(PageNumberPagination):
#     '''
#     继承了PageNumberPagination类，定义了page_size，还有一种方法是可以定义到settings里面一个全局的page_size
#     '''
#     page_size = 2


class PageArticle(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Article.objects.all()
        # 方式一，仅返回数据
        '''
        # 在这里需要实例化类，如果page_size是自定义的类就实例化自定义的类，如果是settings里面的全局就实例化PageNumberPagination这个类
        page_obj = PageNumberPagination()
        result = page_obj.paginate_queryset(queryset, request, self)
        print(result, type(result))
        ser = serializer.PageArticleSerializers(instance=result, many=True)
        return Response(ser.data)
        '''
        # 方式二，数据加分页信息
        '''
        page_obj = PageNumberPagination()
        result = page_obj.paginate_queryset(queryset, request, self)
        print(result, type(result))
        ser = serializer.PageArticleSerializers(instance=result, many=True)
        return page_obj.get_paginated_response(ser.data)
        '''
        # 方式三，数据+部分分页信息
        page_obj = PageNumberPagination()
        result = page_obj.paginate_queryset(queryset, request, self)
        print(result, type(result))
        ser = serializer.PageArticleSerializers(instance=result, many=True)
        return Response({'count': page_obj.page.paginator.count, 'result': ser.data})


class ApiViewArticle(ListAPIView):
    queryset = models.Article.objects.all()
    serializer_class = serializer.ListArticleSerializers
